package com.mofang.ticketing.common.security.component;

import cn.hutool.json.JSONUtil;
import com.mofang.ticketing.common.core.constant.SecurityConstants;
import com.mofang.ticketing.common.redis.constant.RedisConstant;
import com.mofang.ticketing.common.redis.service.RedisService;
import com.mofang.ticketing.common.security.bo.UserDetailBO;
import com.mofang.ticketing.common.security.util.JwtTokenUtil;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * JWT登录授权过滤器
 *
 * @author LGC
 */
public class TokenAuthenticationFilter extends OncePerRequestFilter {
    @Resource
    private JwtTokenUtil jwtTokenUtil;
    @Resource
    private RedisService redisService;

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain chain) throws ServletException, IOException {
        String authHeader = request.getHeader(SecurityConstants.AUTHORIZATION_KEY);
        if (authHeader != null && authHeader.startsWith(SecurityConstants.JWT_PREFIX)) {
            String authToken = authHeader.substring(SecurityConstants.JWT_PREFIX.length());
            String username = jwtTokenUtil.getUserNameFromToken(authToken);
            if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                String loginInfoKey = String.format(RedisConstant.LOGIN_INFO_KEY, username);
                if (redisService.hasKey(loginInfoKey) && redisService.get(loginInfoKey) != null) {
                    UserDetailBO userDetails = JSONUtil.toBean(redisService.get(loginInfoKey).toString(), UserDetailBO.class);
                    if (jwtTokenUtil.validateToken(authToken, userDetails)) {
                        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                        authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                        SecurityContextHolder.getContext().setAuthentication(authentication);
                    }
                }
            }
        }
        chain.doFilter(request, response);
    }
}
